import asyncio
import logging

from aiogram import Bot, Dispatcher
from aiogram.fsm.storage.memory import MemoryStorage
from aiogram.fsm.storage.redis import DefaultKeyBuilder, RedisStorage

from src.bot.handlers import register_handlers
from src.bot.services.logger import configure_logging
from src.bot.services.set_commands import set_commands
from src.bot.services.tg_helpers import broadcast
from src.config import load_config
from src.database.main import sa_sessionmaker

logger = logging.getLogger(__name__)


async def main():
    configure_logging()
    logger.info("Starting bot")

    config = load_config(".env")

    if config.tg_bot.use_redis:
        storage = RedisStorage.from_url(
            url=config.redis.url,
            key_builder=DefaultKeyBuilder(with_destiny=True),
        )
    else:
        storage = MemoryStorage()

    bot = Bot(token=config.tg_bot.token, parse_mode="HTML")
    dp = Dispatcher(storage=storage)
    session_factory = await sa_sessionmaker(config.db, echo=False)

    register_handlers(dp)

    await set_commands(bot)

    await broadcast(bot, config.tg_bot.admin_ids, "Бот запущен!")
    await dp.start_polling(bot, config=config, session_factory=session_factory)


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except (KeyboardInterrupt, SystemExit):
        logger.error("Bot stopped!")
